// ignore_for_file: constant_identifier_names

import 'dart:convert';
import 'dart:typed_data';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:oster_cigarette/common/const/const.dart';
import 'package:oster_cigarette/common/network/exception.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zevent_bus/zevent_bus.dart';

part 'network.api.dart';

enum HTTPMETHOD { GET, POST, PUT, DELETE }

class NetworkTool {
  static String baseURL = AppConst.is_release ? AppConst.host : AppConst.host_test;
  static Dio? _dio;
  static Future<Map<String, dynamic>> request(
    String url, {
    HTTPMETHOD method = HTTPMETHOD.POST,
    Map<String, dynamic>? params,
    bool jsonBody = true,
  }) async {
    // 判断网络
    _dio ??= Dio();
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
    } else if (connectivityResult == ConnectivityResult.wifi) {
    } else if (connectivityResult == ConnectivityResult.none) {
      EasyLoading.showError("当前网络信号不佳");
      throw RequestException(msg: "当前网络信号不佳");
    }

    late Response response;
    String temp = baseURL;
    url = temp + url;
    print("api = $url, param = ${json.encode(params)}, method:$method");
    SharedPreferences share = await SharedPreferences.getInstance();
    String? token = share.getString(AppConst.user_token);

    Options options = Options(contentType: "application/json", headers: {});
    if (token != null) {
      print("token = $token");
      options = Options(contentType: "application/json", headers: {"Authorization": token});
    }
    params ??= {};
    try {
      switch (method) {
        case HTTPMETHOD.POST:
          if (jsonBody) {
            response = await _dio!.post(url, data: json.encode(params), options: options);
          } else {
            FormData formData = FormData.fromMap(params);
            response = await _dio!.post(url, data: formData, options: options);
          }
          break;
        case HTTPMETHOD.GET:
          response = await _dio!.get(url, queryParameters: params, options: options);
          break;
        case HTTPMETHOD.PUT:
          response = await _dio!.put(url, data: params, options: options);
          break;
        case HTTPMETHOD.DELETE:
          response = await _dio!.delete(url, data: params, options: options);
          break;
        default:
      }
    } catch (e) {
      rethrow;
    }

    int? code = response.statusCode;
    if (code == 200) {
      print("jsondata =====> ${json.encode(response.data)}, ${response.data.runtimeType}");
      if (response.data is String) {
        final temp = json.decode(response.data);
        print("=====$temp");
        if (temp["status"] == 403 || temp["status"] == 401) {
          SharedPreferences.getInstance().then((value) => value.clear()); // 清楚用户数据
          EventBus.instance.commit(eventKey: EventKeys.loginOut);
          throw RequestException(code: response.data["status"], msg: response.data["message"]);
        }
        return response.data;
      } else {
        if (response.data["status"] != 200) {
          if (response.data["status"] == 401) {
            SharedPreferences.getInstance().then((value) => value.clear()); // 清楚用户数据
            EventBus.instance.commit(eventKey: EventKeys.loginOut);
            throw RequestException(code: response.data["status"], msg: response.data["message"]);
          } else {
            throw RequestException(
              code: response.data["status"],
              msg: response.data["message"],
              data: response.data["data"],
            );
          }
        } else {
          return response.data;
        }
      }
    } else {
      if (response.data is Map) {
        throw RequestException(msg: response.data["message"]?.toString());
      } else {
        throw RequestException(code: response.data["status"], msg: response.data["message"]);
      }
    }
  }

  // 下载图片到本地
  static downloadImage(String url, {Function(int count, int total)? progress, Function? success}) async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
    } else if (connectivityResult == ConnectivityResult.wifi) {
    } else if (connectivityResult == ConnectivityResult.none) {
      return EasyLoading.showError("当前网络信号不佳");
    }
    var response =
        await Dio().get(url, onReceiveProgress: progress, options: Options(responseType: ResponseType.bytes));
    if (success != null) success(response.data);
  }

  // 上传单个文件
  static Future<Map<String, dynamic>> upload(
    String url,
    String file, {
    HTTPMETHOD method = HTTPMETHOD.POST,
    Map<String, dynamic>? params,
  }) async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
    } else if (connectivityResult == ConnectivityResult.wifi) {
    } else if (connectivityResult == ConnectivityResult.none) {
      EasyLoading.showError("当前网络信号不佳");
      throw RequestException(msg: "当前网络信号不佳");
    }

    late Response response;
    url = baseURL + url;

    SharedPreferences share = await SharedPreferences.getInstance();
    String? token = share.getString(AppConst.user_token);

    Options options = Options();
    params ??= {};
    if (token != null) {
      options = Options(contentType: "multipart/form-data", headers: {"Authorization": token});
    }
    print("$url, $options");
    final fil = await MultipartFile.fromFile(file);
    // final base64data = await Tool.image2Base64(File(file));
    params["file"] = fil;
    FormData formData = FormData.fromMap(params);

    try {
      response = await Dio().post(url, data: formData, options: options);
    } catch (e) {
      throw RequestException(
        msg: "$e",
      );
    }

    int? code = response.statusCode;
    if (code == 200) {
      return response.data;
    } else {
      if (response.data is Map) {
        throw RequestException(msg: response.data);
      } else {
        throw RequestException(msg: response.toString());
      }
    }
  }

  // 上传单个文件
  static Future<Map<String, dynamic>> uploadData(
    String url,
    Uint8List file, {
    HTTPMETHOD method = HTTPMETHOD.POST,
    Map<String, dynamic>? params,
  }) async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
    } else if (connectivityResult == ConnectivityResult.wifi) {
    } else if (connectivityResult == ConnectivityResult.none) {
      EasyLoading.showError("当前网络信号不佳");
      throw RequestException(msg: "当前网络信号不佳");
    }

    late Response response;
    url = baseURL + url;

    SharedPreferences share = await SharedPreferences.getInstance();
    String? token = share.getString(AppConst.user_token);

    Options options = Options();
    params ??= {};
    if (token != null) {
      options = Options(contentType: "multipart/form-data", headers: {"Authorization": token, "lang": "zh"});
    }
    print("$url, $options");
    final fil = MultipartFile.fromBytes(file);
    // final base64data = await Tool.image2Base64(File(file));
    params["file"] = fil;
    FormData formData = FormData.fromMap(params);

    try {
      response = await Dio().post(url, data: formData, options: options);
    } catch (e) {
      throw RequestException(
        msg: "$e",
      );
    }

    int? code = response.statusCode;
    if (code == 200) {
      return response.data;
    } else {
      if (response.data is Map) {
        throw RequestException(msg: response.data);
      } else {
        throw RequestException(msg: response.toString());
      }
    }
  }
}
